package cn.itcast.cloud.storage;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import org.junit.Test;

import java.io.ByteArrayInputStream;

public class ObjectMetaSample {
    private static String endpoint = "http://oss-cn-zhangjiakou.aliyuncs.com";
    private static String accessKeyId = "LTAIXeZktAHXvAgc";
    private static String accessKeySecret = "iHpKZJ5KiB7imcohA7VgjDzLY2O87w";
    private static String bucketName = "jiaze";
    private static String key = "cloud";
    private static String content = "Hello OSS";

    /**
     * 展示文件源信息
     */
    @Test
    public void getObjectMeta(){
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            ObjectMetadata metadata = new ObjectMetadata() ;
            metadata.setContentType("text/plain");
            metadata.setContentMD5("");
            metadata.addUserMetadata("meta", "meta-value");

            ossClient.putObject(bucketName, key, new ByteArrayInputStream(content.getBytes()), metadata) ;

            // Gets the object metadata information.
            ObjectMetadata meta = ossClient.getObjectMetadata(bucketName, key) ;
            System.out.println(meta.getContentType());
            System.out.println(meta.getLastModified());
            System.out.println(meta.getUserMetadata().get("meta"));

            ossClient.deleteObject(bucketName, key);
        }catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message: " + oe.getErrorCode());
            System.out.println("Error Code:       " + oe.getErrorCode());
            System.out.println("Request ID:      " + oe.getRequestId());
            System.out.println("Host ID:           " + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ce.getMessage());
        } finally {
            ossClient.shutdown();
        }
    }
}
